﻿using System;
using System.Reflection;
using Divan;
using libStorage;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace libCouchStorage
{
    class CouchDBDataContainer<T> : CouchDocument
    {

        T _innerData;

        public CouchDBDataContainer(T Data)
        {
            _innerData = Data;
        }

        public CouchDBDataContainer();

        public T getData()
        {
            return _innerData;
        }

        #region CouchDocument Members

        public override void WriteJson(JsonWriter writer)
        {
            // This will write id and rev
            base.WriteJson(writer);

            Type objType = _innerData.GetType();

            writer.WritePropertyName("docType");
            writer.WriteValue(typeof(T).FullName);

            foreach (FieldInfo fieldInfo in objType.GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                foreach (StorableField atrb in fieldInfo.GetCustomAttributes(typeof(StorableField), false))
                {
                    writer.WritePropertyName(atrb.Name);
                    writer.WriteValue(fieldInfo.GetValue(_innerData));
                }
            } 
        }

        public override void ReadJson(JObject obj)
        {
            // This will read id and rev
            base.ReadJson(obj);

            Type objType = _innerData.GetType();

            foreach (FieldInfo fieldInfo in objType.GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                foreach (StorableField atrb in fieldInfo.GetCustomAttributes(typeof(StorableField), false))
                {
                    fieldInfo.SetValue(_innerData, obj[atrb.Name]);                
                }
            } 
        }

        #endregion


    }
}
